import os
import pandas as pd
import cv2
# import numpy as np
from matplotlib import pyplot as plt
import skimage.io
import skimage.filters
from skimage.morphology import disk
# import numpy as np
from skimage.feature import (graycomatrix, graycoprops)

def FeatureCal(path, array):
    gray = CutSludge(path)
    gray=cv2.cvtColor(gray,cv2.COLOR_RGB2GRAY)
    binarypara = graycomatrix(gray, [1], [0], levels=256)
    a = graycoprops(binarypara, 'contrast')
    b = graycoprops(binarypara, 'homogeneity')
    c = graycoprops(binarypara, 'ASM')
    d = graycoprops(binarypara, 'energy')
    e = graycoprops(binarypara, 'correlation')
    f = graycoprops(binarypara, 'contrast')
    array[0].append(a[0][0])
    array[1].append(b[0][0])
    array[2].append(c[0][0])
    array[3].append(d[0][0])
    array[4].append(e[0][0])
    array[5].append(f[0][0])


def HeightCal(path, array):
    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, bn = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    # 反色
    bn1 = cv2.bitwise_not(bn)
    # 找感兴趣区域
    contours, hierarchy = cv2.findContours(bn1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    bounding_boxes = [cv2.boundingRect(cnt) for cnt in contours]
    # heights保存所有感兴趣区域高度
    heights = []
    for bbox in bounding_boxes:
        [x, y, w, h] = bbox
        # 因为我的电脑上图片宽高反过来了 所以这里判断的是W 本来判断的应该是h的 如果出bug可以尝试改这里
        if (h > 20):
            heights.append(h)
        [x, y, w, height] = bbox
        if height > 50:
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 8)
    # ----------  这里是plt把中间的图输出一下 正式情况下是不需要的  暂时注了  --------------
    # plt.figure(figsize=(10, 10))
    # img = img[:, :, [2, 1, 0]]
    # plt.imshow(img)
    # plt.show()
    # ----------------------------------------
    # 排序由大到小
    heights.sort(reverse=True)
    # 把这张图片感兴趣区域(也即是下层污泥)高度最高的那个添加进全局数组中
    array.append(heights[0])


def CutSludge(path):
    img = cv2.imread(path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    ret, bn = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
    bn1 = cv2.bitwise_not(bn)
    contours, hierarchy = cv2.findContours(bn1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    bounding_boxes = [cv2.boundingRect(cnt) for cnt in contours]
    heights = []
    for bbox in bounding_boxes:
        [x, y, w, h] = bbox
        if (h > 20):
            heights.append(w)
        if h > 100:
            # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 8)
            # img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

            # 这里把区域限定的更小一点 以免区域不全是污泥部分
            img = img[y: y + h, x: x + w]
            #  角度问题横坐标加100 再减150
            # img = img[y:y+h,x+100:x + w -150]


            #cv2.imwrite('./cutMud/cutMud'+str(i)+'.jpg',img)
            # 返回截取的污泥部分
            return img
def wuCal(path1,savePath):
    # 孔隙总面积
    SumContourAreaList1 = []
    # 平均孔隙面积
    avgList1 = []
    # 孔隙个数
    contoursList1 = []
    # 孔隙占比
    SumRadioList1 = []

    # SumContourAreaList2 = []
    # avgList2 = []
    # contoursList2 = []
    # SumRadioList2 = []
    #
    # SumContourAreaList3 = []
    # avgList3 = []
    # contoursList3 = []
    # SumRadioList3 = []
    #
    # SumContourAreaList4 = []
    # avgList4 = []
    # contoursList4 = []
    # SumRadioList4 = []

    # 绘图横坐标
    xaixs = []
    count = 0
    for file in os.listdir(path1):  # file 表示的是文件名
        count = count + 1
    for i in range(count):
        preString = path1 + '/picture-'
        xaixs.append(i / 2)
        backString = '.jpg'
        mixPath = preString + str(i) + backString
        rea = CutSludge(mixPath)
        marked = rea.copy()
        gray = cv2.cvtColor(rea, cv2.COLOR_BGR2GRAY)
        # 长宽变化过程中 图片的大小面积实时计算
        sumAera = len(gray[0]) * len(gray[0])
        # gray = exposure.equalize_adapthist(gray, kernel_size=None, clip_limit=0.01, nbins=256)
        gray = skimage.img_as_ubyte(gray, force_copy=False)
        # ret2,th2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
        # ret2,th2 = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.BINA)

        # 此处adaptiveThreshold自适应二值化比OTSU二值化效果更好
        th2 = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 17, 2)
        # th2 = cv2.adaptiveThreshold(gray,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,11,2) #换行符号 \
        # ret,th2=cv2.threshold(gray,50,255,cv2.THRESH_BINARY)
        # 要中值滤波 去除刻度线的干扰
        res = skimage.filters.median(th2, disk(3))
        contours, hierarchy = cv2.findContours(res, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        cv2.drawContours(marked, contours, -1, (0, 0, 255), 1)

        avg = 0
        SumContourArea = 0
        for i in contours:
            SumContourArea += cv2.contourArea(i)
        avg = SumContourArea / len(contours)

        # 全局保存个数 总面积 平均面积
        SumContourAreaList1.append(SumContourArea)
        avgList1.append(avg)
        contoursList1.append(len(contours))
        SumRadioList1.append(SumContourArea / sumAera * 100)



    #HeightCal
    heightTrend1 = []
    heightTrend2 = []
    heightTrend3 = []
    heightTrend4 = []



    count = 0
    for file in os.listdir(path1):  # file 表示的是文件名
        count = count + 1
    print(count)
    print(path1)
    for i in range(count):
        preString = path1 + '/picture-'
        backString = '.jpg'
        mixPath = preString + str(i) + backString
        print(mixPath)
        HeightCal(mixPath, heightTrend1)
    # 最后执行完之后会得到这个视频采样的下层污泥高度变化趋势的数组heightTrend1

    # 由高度变化计算沉降速度每分钟  速度单位是百分比%
    maxHeight1 = heightTrend1[0]
    HeightRate1 = [x / maxHeight1 * 100 for x in heightTrend1]

    xaixs = []
    for i in range(count):
        xaixs.append(i / 2)

    ChenSpeed1 = []
    # 高度速度绘图横坐标
    XaixsSpeed = []
    for i in range(count - 2):
        XaixsSpeed.append(i / 2)
    XaixsSpeed.append(i / 2)
    XaixsSpeed.append(i / 2)
    for i in range(count - 2):
        ChenSpeed1.append(HeightRate1[i] - HeightRate1[i + 2])
    ChenSpeed1.append(HeightRate1[i] - HeightRate1[i + 2])
    ChenSpeed1.append(HeightRate1[i] - HeightRate1[i + 2])



    AAO1 = [[], [], [], [], [], []]
    AAOYuan = [[], [], [], [], [], []]
    YangHua1 = [[], [], [], [], [], []]
    YangHua = [[], [], [], [], [], []]

    count = 0
    for file in os.listdir(path1):  # file 表示的是文件名
        count = count + 1
    for i in range(count):
        preString = path1 + '/picture-'

        backString = '.jpg'
        # print(preString + str(i) + backString)
        mixPath = preString + str(i) + backString

        FeatureCal(mixPath, AAO1)

    data = pd.DataFrame()
    data['HeightRate1'] = HeightRate1
    data['XaixsSpeed'] = XaixsSpeed
    data['ChenSpeed1'] = ChenSpeed1
    data['SumContourArea'] = SumContourAreaList1
    data['avg'] = avgList1
    data['num'] = contoursList1
    data['SumRadio']=SumRadioList1
    data['dissimilarity'] = AAO1[0]
    data['homogeneity'] = AAO1[1]
    data['ASM'] = AAO1[2]
    data['energy'] = AAO1[3]
    data['correlation'] = AAO1[4]
    data['contrast'] = AAO1[5]
    data['xaixs'] = xaixs


    # data['fenxing'] = fenxing
    data.to_excel(savePath + '/excel.xlsx')
